import React, { useState, useEffect } from 'react';
import {
  FileExcelOutlined, MinusSquareOutlined,
  PlusSquareOutlined, EditOutlined} from '@ant-design/icons';
import { Select, Button, Spin, DatePicker } from 'antd';
import { createFromIconfontCN } from '@ant-design/icons';
import { useHistory } from 'react-router-dom';

import {
  openNotification_util, fetchsync_util, useexcelauto,
  dealnullorundenfined,dealnullorundenfinedmx,
  convertISODateTimeToYYYYMMDDHHMMSS,convertISODateTimeToYYYYMMDD
} from '../util/util.js'
import Custom_table_hooks_config from '../newmes/custom_table_hooks_config.js'
var storage = window.localStorage;
const { Option } = Select;
import Sortable from '../newmes/sortable.js';
import { use_qtck_initcolmun, use_qtck_mx_initcolmun } from './use_kc_config.js';
import moment from 'moment'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')
import locale from 'antd/lib/date-picker/locale/zh_CN'
import { useLatest } from 'ahooks';
import useStore from '../../useStore.js'
import { clearCache,useDidCache,useDidRecover ,dropByCacheKey } from 'react-router-cache-route';

const IconFont = createFromIconfontCN({
  scriptUrl: 'http://111.77.154.58:2233/icon.js',
});

const Qtck_list = () => {
  const history = useHistory();
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [isloading, setisloading] = useState(false)
  const [initSize, setinitSize] = useState() //table宽度大小
  const [ifshow, setifshow] = useState(true)
  const [listdata, setlistdata] = useState([])
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [columnarr, setcolumnarr] = useState(use_qtck_mx_initcolmun)
  const [startDataStr, setStartDataStr] = useState()
  const [endDataStr, setEndtDataStr] = useState()
  const startDataStrref=useLatest(startDataStr)
  const endDataStrref=useLatest(endDataStr)
  const [ifmx, setifmx] = useState(false)
  const { nowroute, setnowroute,collapsed,setcollapsed } = useStore();

  useEffect(() => {
    querylist("mx")
    setifmx(true)
    storage[`Pc_qtck_list${'_'+storage.userid}`] ? setcolumnarr(JSON.parse(storage[`Pc_qtck_list${'_'+storage.userid}`])) : setcolumnarr(columnarr)
    storage[`Pc_qtck_list_initsize${'_'+storage.userid}`] ? setinitSize(storage[`Pc_qtck_list_initsize${'_'+storage.userid}`]) : setinitSize(1)
  }, [])

  useEffect(() => { ifshow ? "" : setifshow(true) }, [ifshow])

  //路由跳转
  const tonormal = (route) => {history.push({ pathname: route });}

  const querylist = async (type) => {
    setisloading(true)
    console.log(type)
    let rtdata = await fetchsync_util("/admin/kcgl/qtck_list", 'POST', {type,startDataStrref:startDataStrref.current,endDataStrref:endDataStrref.current}, "json")
    // openNotification_util(rtdata.rtmessage)
    rtdata.resultdata.forEach(element => {
      element.create_time = convertISODateTimeToYYYYMMDDHHMMSS(element.create_time)
      element.update_time = convertISODateTimeToYYYYMMDDHHMMSS(element.update_time)
      element.create_timeq = convertISODateTimeToYYYYMMDD(element.create_timeq)

    });
    if(type=="mx"){
      setlistdata(dealnullorundenfinedmx(rtdata.resultdata))
    } else {
      setlistdata(dealnullorundenfined(rtdata.resultdata))
    }
    setselectedRowKeys([])
    setselectedRows([])
    setifshow(false)
    setisloading(false)
  }

  /**手动查询*/
  const handleQuery = async () => {
    setcolumnarr(use_qtck_initcolmun)
    setifmx(false)
    querylist()
  }
  /**手动查询*/
  const handleQuerymx = async () => {
    setcolumnarr(use_qtck_mx_initcolmun)
    setifmx(true)
    querylist("mx")
  }
  /**新增*/
  const handleadd = async () => {
    storage.pre_qtck_item = JSON.stringify({ data: {}, type: "add" })
    dropByCacheKey("qtck_form")
    setnowroute({route:"/shipSRM/kcgl/qtck_form",title:"其他出库_新增"})  
   }
  /**编辑*/
  const handleEdit = async () => {
    if (selectedRows.length !== 1) {
      openNotification_util("只可选择一条数据编辑!")
    }
    else {
      storage.pre_qtck_item = JSON.stringify({ data: selectedRows[0], type: "edit" })
      dropByCacheKey("qtck_form")
      setnowroute({route:"/shipSRM/kcgl/qtck_form",title:"其他出库_编辑"})   
    }
  }
  /**删除*/
  const handledelete = async () => {
      let rtdata = await fetchsync_util("/admin/kcgl/delete_qtck", 'POST', { selectedRows }, "json")
      rtdata.rtstatus ? querylist("mx") : 1
  }
  /**导出*/
  const handleExport = async () => {
    useexcelauto(selectedRows, columnarr, '在线表单')
  }

  return (
    <div style={{    height: "94%", backgroundColor: `#F1F1F1`,right:"1%",top:"4vh",overflow:"hidden",
      backgroundSize: "100% 100%", width: collapsed?"94%":"84%", position: "absolute",  color: "white", fontSize: "0.8rem"}}>
      <div style={styles.kshcontainer}>
        <div style={{
          width: "99vw", height: "", backgroundColor: "white", overflowX: "scroll", margin: "0.5vw",
          paddingLeft: "1vw"
        }}>
          <div style={styleobj.linestyleflex}>
            &nbsp;<span style={{ fontSize: "0.8vw", fontWeight: "800" ,color: "#a91f24"}}>开始日期：</span><DatePicker locale={locale} 
            style={{ width: "200px" }} onChange={(e, dateString) => setStartDataStr(dateString)} /> &nbsp;
          <span style={{ fontSize: "0.8vw", fontWeight: "800" ,color: "#a91f24"}}>结束日期：</span> <DatePicker locale={locale} 
            style={{ width: "200px" ,}} onChange={(e, datestring) => setEndtDataStr(datestring)} />  &nbsp;
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => { isloading ? openNotification_util("请等待数据查询完成再操作！") : handleQuerymx() }}>
              <SearchOutlined />明细</Button>
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleadd}>
              <PlusSquareOutlined />新 增</Button>
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleEdit}>
              <EditOutlined /> 编 辑 </Button>
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handledelete}>
              <MinusSquareOutlined /> 删 除</Button>
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleExport}>
              <FileExcelOutlined />导 出</Button>
          </div>
          <IconFont type="setting" style={{ position: 'absolute', right: '2vw', top: '0.5rem', fontSize: "1.5rem" }}
            onClick={e => setIsModalOpen(true)} />
          {ifshow && <Sortable tableColnum={columnarr} handleTableColomn={(data) => { setcolumnarr(data); }}
            storageName={`Pc_qtck_list${'_'+storage.userid}`} open={isModalOpen} handleOpen={(data) => { setIsModalOpen(data); }}
            initSize={initSize} handleInitSize={(data) => { setinitSize(data); storage[`Pc_qtck_list_initsize${'_'+storage.userid}`] = data; }}
          />}
          {isloading ?
            (<div style={{ width: "10%", height: "10%", position: "absolute", left: "50%", top: "49%", color: "#14d9cc" }}>
              <Spin /></div>)
            :
            (<Custom_table_hooks_config tabledata={listdata} tablecolnum={columnarr}
              width={collapsed?"94%":"84%"}
              sfdoubleclick="false" ifhiddencchangeselecttype="true"
              selectedRows={selectedRows} selectedRowKeys={selectedRowKeys}
                defaultPageSize={10}
              bordered
              scroll={{ y: 'calc(100vh - 280px)', x: initSize * 1650 }}
              handleselectson={(selectedRows, selectedRowKeys) => {
                setselectedRows(selectedRows)
                setselectedRowKeys(selectedRowKeys)
              }}
            />)
          }
        </div>
      </div>
    </div>
  )
}

export default Qtck_list

var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `#F1F1F1`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
  topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
  butdcstyle: { paddingLeft:"1.5vw",paddingRight:"1.5vw", height: "2vw", position: "absolute", 
    right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },
  butmainstyle: { paddingLeft:"1.5vw",paddingRight:"1.5vw", 
    height: "2vw", position: "absolute", right: "8%", top: "0%", 
    backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },
  kshcontainer: {
    width: "100%", minHeight: "40vh", position: "absolute", 
    top: "2vh", left: "0vw", backgroundColor: "#F1F1F1",
    color: "black"
  },
}
var styleobj = {
  linestyle: { height: "1.8rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },
  linestylesmall: { height: "1.3rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },
  linestyleflex: {
    height: "1.8rem", fontSize: "0.6rem", position: "relative", width: "96vw", marginLeft: "0.1%",
    display: "flex", justifyContent: "flex-start", alignItems: "center", marginBottom: "0.5rem",marginTop:"0.5rem"
  },
  linestyleflexitem: {
    height: "1.6rem", fontSize: "0.7rem", position: "relative", width: "23%", textIndent: "0.5rem",
    backgroundColor: "white", lineHeight: "1.6rem", fontSize: "0.75rem", fontWeight: "500", textAlign: "center"
  },
  linestyleflexitemleft: { backgroundColor: "#F0F0F0", position: "absolute", width: "35%", left: "0" },
  linestyleflexitemright: { backgroundColor: "white", position: "absolute", width: "64%", right: "0" },
  lineleft: { width: "100%", height: "100%", position: "absolute", left: "0%", 
    textAlign: "left", lineHeight: "2rem", fontSize: "0.75rem", fontWeight: "700" },
}